package com.SmartCare.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.SmartCare.common.enums.Constants;
import com.SmartCare.common.Result;
import com.SmartCare.common.exception.ServiceException;
import com.SmartCare.service.MailService;
import com.SmartCare.mapper.role.UserMapper;
import com.SmartCare.pojo.role.User;
import com.SmartCare.utils.ValidateCodeUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Service
@Slf4j
public class MailServiceImpl implements MailService {
    //把yml配置的邮箱号赋值到from
    @Value("${spring.mail.username}")
    private String from;
    //发送邮件需要的对象
    @Autowired
    private JavaMailSender javaMailSender;

    @Resource
    private RedisTemplate redisTemplate;

    @Resource
    private UserMapper userMapper;

    //邮件发送人
    @Override
    public void sendMsg(String to, String subject, String text) {
        //发送简单邮件，简单邮件不包括附件等别的
        SimpleMailMessage message = new SimpleMailMessage();
        message.setFrom(from);
        message.setTo(to);
        message.setSubject(subject);
        message.setText(text);
        //发送邮件
        javaMailSender.send(message);
    }


    @Override
    public Result managerSendCode(String mail, String purposes) {
        //设置正则表达式
        String regEx1 = "^([a-z0-9A-Z]+[-|\\.]?)+[a-z0-9A-Z]@([a-z0-9A-Z]+(-[a-z0-9A-Z]+)?\\.)+[a-zA-Z]{2,}$";
        Pattern p;
        Matcher m;
        p = Pattern.compile(regEx1);
        m = p.matcher(mail);
        if (!m.matches()) {
            throw new ServiceException(Constants.CODE_400, "邮箱格式不合法");
        }
        //生成验证码
        String code = ValidateCodeUtils.generateValidateCode(6).toString();
        String text = "";
        switch (purposes) {
            case "LOGIN": {
                text = "【至孝养老】后台管理系统登录验证码：" + code + ", 5分钟内有效, 请按页面提示提交验证码, 切勿将验证码泄露于他人。";
                break;
            }
            case "SIGN": {
                text = "【至孝养老】后台管理系统注册验证码：" + code + ", 5分钟内有效, 请按页面提示提交验证码, 切勿将验证码泄露于他人。";
                break;
            }
            case "CHANGE": {
                text = "【至孝养老】您正在后台管理系统修改登录密码，验证码：" + code + ", 5分钟内有效, 请按页面提示提交验证码, 切勿将验证码泄露于他人。";
            }
        }
        log.info("后台验证码为：" + code);
        try {
            //发送短信
            sendMsg(mail, "至孝养老", text);
            //将生成的验证码缓存到redis中，并且设置有效时间为5分钟
            redisTemplate.opsForValue().set(mail + purposes, code, 5, TimeUnit.MINUTES);
            log.info("Redis中保存的验证码为：" + redisTemplate.opsForValue().get(mail + purposes));
        } catch (Exception e) {
            log.error("邮件发送失败" + e);
            throw new ServiceException(Constants.CODE_500, "邮件发送失败");
        }
        return Result.success();
    }

    @Override
    public Result managerVerifyCode(String mail, String code, String purposes) {
        //从redis中获取对应的验证码
        String save = (String) redisTemplate.opsForValue().get(mail + purposes);
        if (code.equals(save)) {
            if (purposes.equals("LOGIN")) {
                //如果是登录，需要获取用户信息并返回
                User one = userMapper.selectOne(new QueryWrapper<User>().eq("mail", mail));
                if (one != null) {
                    return Result.success(one);
                }else{
                    return Result.error("不存在绑定了该邮箱的用户");
                }
            }
            //不为登录则直接返回
            return Result.success();
        } else {
            return Result.error("验证码错误");
        }
    }

    /**
     * 获取邮箱登录验证码
     * @param mail 邮箱地址
     */
    @Override
    public Result getAuthCode(String mail) {
        String subject = "至孝养老";
        //参数请求判断
        if (StringUtils.isNotEmpty(mail)) {
            //发送一个四位数的验证码,把验证码变成String类型
            String code = ValidateCodeUtils.generateValidateCode(6).toString();
            String text = "【至孝养老】您的验证码为：" + code + "，有效时间为5分钟，请按页面提示提交验证码，切勿将验证码泄露于他人。";
            log.info("验证码为：" + code);
            //发送短信
            sendMsg(mail, subject, text);
            //将生成的验证码缓存到redis中，并且设置有效时间为5分钟
            redisTemplate.opsForValue().set(mail, code, 5, TimeUnit.MINUTES);

            return Result.success("验证码发送成功");
        }
        return Result.error("验证码发送异常，请重新发送");
    }
}
